package com.crane.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

/**
 * 编号生成工具
 *
 * @author marcelo
 * @date 2020/9/3
 */
public class CodeUtils {

    /**
     * 获取最新备件编号
     *
     * @param oldCode
     * @param length
     * @return
     */
    public static String getPartCode(String oldCode, int length) {
        String code = "";
        if (StringUtils.isBlank(oldCode)) {
            code = "0";
        } else {
            code = minusZeroForNum(oldCode.substring(5));
        }
        StringBuilder sn = new StringBuilder("B").append(LocalDate.now().getYear());
        sn.append(addZeroForNum(code, length));
        return sn.toString();
    }

    /**
     * 数字补足零
     *
     * @param str
     * @param length
     * @return
     */
    public static String addZeroForNum(String str, int length) {
        return String.format("%0" + length + "d", Integer.parseInt(str) + 1);
    }

    /**
     * 去除字符串数字前面的零
     *
     * @param str
     * @return
     */
    public static String minusZeroForNum(String str) {
        return str.replaceAll("^(0+)", "");
    }

    /**
     * 编号生成
     *
     * @param type
     * @return
     */
    public static String getSn(String type) {
        StringBuilder sn = new StringBuilder();
        sn.append(type).append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHH"))).append(String.format("%04d", new Random().nextInt(9999)));
        return sn.toString();
    }

    /**
     * 获取最新出入库编号
     *
     * @param oldCode
     * @param length
     * @return
     */
    public static String getPartRecordCode(String oldCode, int length, String prefix, int num) {
        String code = "";
        if (StringUtils.isBlank(oldCode)) {
            code = "0";
        } else {
            code = minusZeroForNum(oldCode.substring(num));
        }
        StringBuilder sn = new StringBuilder(prefix).append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
        sn.append(addZeroForNum(code, length));
        return sn.toString();
    }
    
    public static void main(String []args) {
    	System.out.println(CodeUtils.getSn("EP"));
    }
    
}
